<?php
    namespace Assist\Controller;
    use User\Api\UserApi;
    use Think\Log;
    class InsuranceController extends AssistController {
        
        public function area($province=''){
            if(empty($province)){
                $this->error('未指定省份');
            }
            $model = M('ProvinceArea');
            $where['province_id'] =$province;
            $where['status'] = 1;
            $res = $model->where($where)->order('car_prefix')->select();
            $this->success($res,'');
        }
        
        /**
        * 购险首页
        * 
        */
        public function index(){
            if(IS_POST){
                set_time_limit(60);//设置最长执行时间60秒
                //首先要获得车型
                $params = I('post.');
                if(empty($params['c_new_vhl'])){
                    $params['c_lcn_no'] = $params['car_prefix'] . $params['c_lcn_no'];
                    $params['c_new_vhl'] = '0';
                    
                    $params['fuel_type'] = '0';
                }else{
                    $params['c_lcn_no'] = '*-*';
                }
                unset($params['car_prefix']);
                
                //保存输入信息至session
                $insurace_data = array(
                    'input_params' => $params,
                );                
                session('insurace_data',$insurace_data);
                
                $cicService = D('Cic','Service');
                $ret = $cicService->getVehicleInfo($params);
                if($ret){
                    if(count($ret) == 1){ //如果只有一种车型
                        $veh_info = array();
                        foreach($ret[0] as $key => $val){
                            $veh_info[strtolower($key)] = $val;
                        }
                        
                        //保存车辆信息至session
                        $insurace_data['veh_info'] = $veh_info;
                        session('insurace_data',$insurace_data);
                        
                        $in_params = array_merge($params,$veh_info);
                        $ret = $cicService->getScheme($in_params);
                        if($ret){
                            //保存投保方案至session
                            $insurace_data['scheme_list'] = $ret;
                            session('insurace_data',$insurace_data);
                            
                            $kinds = array();
                            foreach($ret['KIND_LIST']['KIND'] as $kind){
                                unset($data);
                                $data = array(
                                    'c_kind_cde' => $kind['C_KIND_CDE'],
                                    'n_amt' => $kind['N_DEFAULT_AMT'],
                                    'n_seat_num' => $kind['N_SEAT_NUM'],
                                );
                                $kinds[$kind['C_KIND_CDE']] = $data;
                            }
                            
                            //默认方案计算金额
                            $c_order_no = $ret['BASE']['C_ORDER_NO'];
                            if($ret['BASE'] && $ret['BASE']['C_LAST_BUS_END']){
                                $dtReg = new \DateTime($ret['BASE']['C_LAST_BUS_END']);
                                $dtReg = $dtReg->add(new \DateInterval('P1D'));
                                $t_insrnc_bgn_tm = $dtReg->format('Y-m-d 00:00:00');
                                $t_traff_bgn_tm = $dtReg->format('Y-m-d 00:00:00');
                            }
                            
                            $calc_params = array(
                                'c_dpt_cde' => $params['c_dpt_cde'],
                                'c_order_no' => $c_order_no,
                                't_insrnc_bgn_tm' => $t_insrnc_bgn_tm,
                                't_traff_bgn_tm' => $t_traff_bgn_tm,
                                
                                'kinds' => $kinds,
                                'fuel_type' => $params['fuel_type'],
                                'buy_date' => $params['buy_date'],
                            );
                            
                            $ret = $cicService->calcFee($calc_params);
                            if($ret){
                                //保存投保方案至session
                                $insurace_data['calc_result'] = $ret;
                                session('insurace_data',$insurace_data);                                
                            }
                            $this->success('成功',U('selectScheme'));
                        }else{
                            $this->error($cicService->error);
                        }
                    }else{//如果返回车型太多的话需要选择下
                        //TODO:车型选择太多的时候弹出对话框选择
                        //当前仅返回错误信息
                        /*
                        session('vehicle_list',$ret);
                        $this->success('成功',U('selectVehicle'));
                        */
                        $this->error('车辆类型太多，请检查数据信息！');
                    }
                }else{
                    $this->error($cicService->error);
                }
            }else{
                $uid = is_login();
                if($uid){
                    $user = M('Member')->where("uid=$uid")->find();
                    $this->assign('user',$user);
                }
                
                //车辆品牌用
                $brands = M('CarBrand')->field('brand_id,brand_name,brand_alpha')->order('brand_alpha,brand_id')->select();
                //省份
                $province = M('Province')->select();
                
                $this->assign('province',$province);
                $this->assign('brands',$brands);
                $this->display();
            }
        }
        
        /**
        * 选择车辆类型
        * 
        */
        public function selectVehicle(){
            if(IS_POST){
                
            }else{
                $vhlmodel_list = session('vehicle_list');
                $this->assign('vhlmodel_list',$vhlmodel_list);
                $this->display();
            }
        }
        
        /**
        * 选择方案页面
        * 
        */
        public function selectScheme(){
            if(IS_POST){
                $kinds = I('post.kinds');
                foreach($kinds as &$kind){
                    if(empty($kind['flag'])){
                        $kind['n_amt'] = $kind['noflag'];
                    }
                    unset($kind['flag']);
                    unset($kind['noflag']);
                }
                //从session获取原来输入的信息
                $insurace_data = session('insurace_data');
                $c_dpt_cde = $insurace_data['input_params']['c_dpt_cde'];
                $c_fst_reg_dte = $insurace_data['input_params']['c_fst_reg_dte'];
                $fuel_type = $insurace_data['input_params']['fuel_type'];
                $buy_date = $insurace_data['input_params']['buy_date'];
                $c_order_no = $insurace_data['scheme_list']['BASE']['C_ORDER_NO'];
                if($insurace_data['scheme_list']['BASE'] && $insurace_data['scheme_list']['BASE']['C_LAST_TRA_END']){
                    $t_insrnc_bgn_tm = $insurace_data['scheme_list']['BASE']['C_LAST_TRA_END'];
                    $t_traff_bgn_tm = $insurace_data['scheme_list']['BASE']['C_LAST_TRA_END'];
                }else{
                    $now = new \DateTime();
                    $dtReg = new \DateTime($c_fst_reg_dte);
                    while($dtReg->getTimestamp()<$now->getTimestamp()){
                        //如果首登日期大于今天，则直接首登日期否则一年一年累加
                        $dtReg = $dtReg->add(new \DateInterval('P1Y'));
                    }
                    $t_insrnc_bgn_tm = $dtReg->format('Y-m-d 00:00:00');
                    $t_traff_bgn_tm = $dtReg->format('Y-m-d 00:00:00'); 
                }
                $calc_params = array(
                    'c_dpt_cde' => $c_dpt_cde,
                    'c_order_no' => $c_order_no,
                    't_insrnc_bgn_tm' => $t_insrnc_bgn_tm,
                    't_traff_bgn_tm' => $t_traff_bgn_tm,
                    
                    'kinds' => $kinds,
                    'fuel_type' => $fuel_type,
                    'buy_date' => $buy_date,
                );
                $cicService = D('Cic','Service');
                $ret = $cicService->calcFee($calc_params);
                if($ret){
                    //保存投保方案至session
                    $insurace_data['calc_final'] = $ret;
                    session('insurace_data',$insurace_data);
                    $this->success('ok',U('verifyInfo'));
                }else{
                    $this->error($cicService->error);
                }
            }else{
                //显示选择页面
                $insurace_data = session('insurace_data');
                $ret = $insurace_data['scheme_list'];
                $c_order_no = $ret['BASE']['C_ORDER_NO'];
                
                //排序表
                $orderlist = array(
                    array('030018','031902'), //机动车第三者责任保险,不计免赔特约条款（三者险）
                    array('030006','031901'), //机动车损失保险,不计免赔特约条款（车损险）
                    array('030070','033531'), //机动车车上人员责任保险（司机）,不计免赔特约条款（车上人员司机）
                    array('030072','033532'), //机动车车上人员责任保险（乘客）,不计免赔特约条款（车上人员乘客）
                    array('030059','030106'), //机动车盗抢保险,不计免赔特约条款（盗抢险）
                    array('030004',''), //玻璃单独破碎险
                    array('030025','031911'), //车身划痕损失险,不计免赔特约条款（车身划痕险）
                    array('030012','031903'), //自燃损失险,不计免赔特约条款（自燃险）
                    array('030065','030125'), //涉水发动机损坏险,不计免赔特约条款（涉水发动机损坏险）
                    array('033535',''), //指定专修厂特约条款
                );
                
                $scheme_zl = array(
                    array('030018','031902'), //机动车第三者责任保险,不计免赔特约条款（三者险）
                    array('030006','031901'), //机动车损失保险,不计免赔特约条款（车损险）
                    array('030059','030106'), //机动车盗抢保险,不计免赔特约条款（盗抢险）
                    array('030012','031903'), //自燃损失险,不计免赔特约条款（自燃险）
                );
                $scheme_jb = array(
                    array('030018','031902'), //机动车第三者责任保险,不计免赔特约条款（三者险）
                    array('030006','031901'), //机动车损失保险,不计免赔特约条款（车损险）
                );
                
                $kindlist = array();
                foreach($orderlist as $o){
                    $k = array();
                    //查找主险
                    foreach($ret['KIND_LIST']['KIND'] as $kind){
                        if($kind['C_KIND_CDE']==$o[0]){
                            $kind['opts'] = json_decode($kind['C_AMT_LIST'],true);
                            $k = $kind;
                            break;
                        }
                    }             
                    if(empty($k) || empty($o[1])){
                        
                    }else{
                        //有不计免赔项
                        foreach($ret['KIND_LIST']['KIND'] as $kind){
                            if($kind['C_KIND_CDE']==$o[1]){
                                $kind['opts'] =json_decode($kind['C_AMT_LIST'],true);
                                $k['bjmp'] = $kind;
                                break;
                            }
                        }             
                    }
                    if(!empty($k)){
                        $kindlist[] = $k;
                    }
                }
                if(empty($insurace_data['calc_result'])){
                    $this->assign('calc_result','null');
                }else{
                    $calc_result = $insurace_data['calc_result'];
                    foreach($calc_result['KIND_LIST']['KIND'] as &$kind){
                        unset($kind['C_KIND_NAME']);
                    }
                    $this->assign('calc_result',json_encode($calc_result));                    
                }
                
                $this->assign('scheme_jb',json_encode($scheme_jb));
                $this->assign('scheme_zl',json_encode($scheme_zl));
                $this->assign('scheme_qm',json_encode($orderlist));
                $this->assign('kindlist',$kindlist);
                $this->assign('c_order_no',$c_order_no);
                $this->display();
            }
        }
        
        protected function getSexFromIdentno($ident_no){
            $len = strlen($ident_no);
            if( $len == 15){
                $flag = substr($ident_no,-1);
            }else if($len == 18){
                $flag = substr($ident_no,-2,1);
            }
            if(($flag % 2) == 1){
                return '1061';
            }else{
                return '1062';
            }
        }
        
        public function verifyInfo(){
            if(IS_POST){
                $mobile = I('mobile');
                $aid = I('aid');
                if(empty($mobile)){
                    $this->error('请填写手机号码！');
                }
                if(!preg_match("/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/",$mobile)){    
                    $this->error('手机号码格式不正确！');
                }
                $c_drv_owner = I('c_drv_owner');
                if(empty($c_drv_owner)) $this->error('车主姓名未填写！');
                $c_ident_no = trim(I('c_ident_no'));
                if(empty($c_ident_no)) $this->error('身份证号码未填写！');
                $c_payment_type = I('c_payment_type');
                if(empty($c_payment_type)) $this->error('请选择支付方式！');
                
                $model = M('UserAddress');
                $uid = is_login();
                if(empty($uid)){//如果用户未登陆
                    $verify = I('verify');
                    if(empty($verify)){
                        $this->error('验证码不能为空！');
                    }
                        /* 调用UC登录接口登录 */
                    $user = new UserApi;
                    $uid = $user->login($mobile, $verify, 5);
                    if(0 < $uid){ //UC登录成功
                        /* 登录用户 */
                        $Member = D('Member');
                        if($Member->login($uid)){ //登录用户
                        } else {
                            $this->error($Member->getError());
                        }
                    }else{
                        $this->error('用户登录出错！');
                    }
                    
                    //先保存session中的地址列表到用户列表中
                    $addr_list = session('addr_list');
                    foreach($addr_list as $addr){
                        if($addr['aid'] == $aid){
                            $address = $addr['province'] .$addr['city'].$addr['area'].$addr['address'];
                            $c_contact_name = $addr['recvname'];
                            $c_contact_tel = $addr['mobile'];
                        }
                        unset($addr['aid']);
                        $addr['uid'] = $uid;
                        $model->add($addr);
                    }
                }else{
                    $resAddress = $model->where("aid=$aid")->find();
                    if($resAddress){
                        $address = $resAddress['province'] .$resAddress['city'].$resAddress['area'].$resAddress['address'];
                        $c_contact_name = $resAddress['recvname'];
                        $c_contact_tel = $resAddress['mobile'];
                    }else{
                        $this->error('错误的地址！');
                    }
                }
                
                //从session获取原来输入的信息
                $insurace_data = session('insurace_data');
                $c_dpt_cde = $insurace_data['input_params']['c_dpt_cde'];
                $c_order_no = $insurace_data['scheme_list']['BASE']['C_ORDER_NO'];
                $sex = $this->getSexFromIdentno($c_ident_no);
                $email = 'gxjl@icarforce.com';
                $params = array(
                    'c_dpt_cde' => $c_dpt_cde,
                    'c_order_no' => $c_order_no,
                    'c_drv_owner' => $c_drv_owner,
                    'c_ident_type' => '01',
                    'c_ident_no' => $c_ident_no,
                    'c_app_nme' => $c_drv_owner,
                    'c_app_sex' => $sex,
                    'c_app_ident_type' => '01',
                    'c_app_ident_no' => $c_ident_no,
                    'c_app_tel' => $mobile,
                    'c_app_addr' => $address,
                    'c_app_email' => $email,
                    'c_insrnt_nme' => $c_drv_owner,
                    'c_insrnt_sex' =>$sex,
                    'c_insrnt_ident_type' => '01',
                    'c_insrnt_ident_no' => $c_ident_no,
                    'c_insrnt_tel' => $mobile,
                    'c_insrnt_addr' => $address,
                    'c_insrnt_email' => $email,
                    'c_contact_name' => $c_contact_name,
                    'c_contact_tel' => $c_contact_tel,
                    'c_contact_email' => $email,
                    'c_address' => $address,
                );
                Log::record('verifyInfo:params:'.print_r($params,true));
                $cicService = D('Cic','Service');
                $ret = $cicService->verifyInfo($params);
                if($ret){
                    $confirm_params = array(
                        'c_order_no' => $c_order_no,
                    );
                    $ret = $cicService->confirm($confirm_params);
                    if($ret){
                        $buy_params = array(
                            'c_order_no' => $c_order_no,
                            'c_payment_type' => $c_payment_type,
                        );
                        $ret = $cicService->buy($buy_params);
                        if($ret){
                            if($c_payment_type == '01'){
                                $url = C('CIC_PAY_URL').$c_order_no;
                            }else{
                                $url = U('User/index');
                            }
                            $this->success('ok',$url);
                        }
                    }else{
                        $this->error($cicService->error);
                    }
                }else{
                    $this->error($cicService->error);
                }
                
            }else{
                //从session获取原来输入的信息
                $insurace_data = session('insurace_data');
                $c_lcn_no = $insurace_data['input_params']['c_lcn_no'];
                $c_fst_reg_dte = $insurace_data['input_params']['c_fst_reg_dte'];
                $fuel_type = $insurace_data['input_params']['fuel_type'];
                $buy_date = $insurace_data['input_params']['buy_date'];
                $c_order_no = $insurace_data['scheme_list']['BASE']['C_ORDER_NO'];
                $c_drv_owner = $insurace_data['input_params']['c_drv_owner'];
                $this->assign('order_date',date('Y-m-d'));
                $this->assign('c_lcn_no',$c_lcn_no);
                $this->assign('vhlinfo',$insurace_data['veh_info']);
                $this->assign('c_drv_owner',$c_drv_owner);
                $this->assign('calc_result',$insurace_data['calc_final']);
                
                $uid = is_login();
                if($uid){
                    $modelAddress = M('UserAddress');
                    $where['uid'] = $uid;
                    $address = $modelAddress->where($where)->select();
                    $this->assign('address',$address);
                    $modelMember = M('Member');
                    $user = $modelMember->where("uid=$uid")->find();
                    $this->assign('user',$user);
                }else{
                    $address = session('addr_list');
                    $this->assign('address',$address);
                }
                
                $this->display();
            }
        }

        
        /**
        * 地址管理
        * 
        */
        public function address(){
            if(IS_POST){
                //登录用户的话用数据库的
                $uid = is_login();
                if($uid){
                    $model = M('UserAddress');
                    $data = $model->create();
                    $data['uid'] = $uid;
                    $ret = $model->add($data);
                    if($ret){
                        $data['aid'] = $ret;
                    }
                    $this->success($data);
                }else{
                    //否则用session
                    $addr_list = session('addr_list');
                    if(empty($addr_list)){
                        $addr_list = array();
                    }
                    $model = M('UserAddress');
                    $data = $model->create();
                    $data['aid'] = count($addr_list);
                    $addr_list[] = $data;
                    session('addr_list',$addr_list);
                    $this->success($data);
                }
            }
        }
        
        /**
        * 购险第二步
        * 
        */
        public function step2(){
            $mobile = I('mobile');
            if(empty($mobile)){
                $this->error('请填写手机号码！');
            }
            if(!preg_match("/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/",$mobile)){    
                $this->error('手机号码格式不正确！');
            }

            $uid = is_login();
            if(empty($uid)){//如果用户未登陆
                $verify = I('verify');
                if(empty($verify)){
                    $this->error('验证码不能为空！');
                }
                    /* 调用UC登录接口登录 */
                $user = new UserApi;
                $uid = $user->login($mobile, $verify, 5);
                if(0 < $uid){ //UC登录成功
                    /* 登录用户 */
                    $Member = D('Member');
                    if($Member->login($uid)){ //登录用户
                    } else {
                        $this->error($Member->getError());
                    }
                }
            }
            
            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            $c_dpt_cde = I('c_dpt_cde');
            $c_new_vhl = I('c_new_vhl',0);
            $c_lcn_no = I('c_prefix').I('c_lcn_no');
            if($c_new_vhl){
                $c_lcn_no = '*-*';
            }
            $sex = I('sex','1061');
            $brand = I('brand');
            $series = I('series');
            $model = I('model');
            
            $modelBrand = M('CarBrand');
            $c_brnd_cde = $modelBrand->where("brand_id=$brand")->getField('brand_name');
            /*
            $modelSeries = M('CarSeries');
            $eng_name = $modelSeries->where("series_id=$series")->getField('eng_name');
            $modelModel = M('CarModel');
            $model_name = $modelModel->where("model_id=$model")->getField('model_name');
            if(!empty($eng_name)){
                $c_brnd_cde = $eng_name;
            }
            //$c_brnd_cde = $model_name;
            */
            //$c_brnd_cde = 'HG730';
            
            $c_eng_no = I('c_eng_no');
            $c_vhl_frm = I('c_vhl_frm');
            //$c_brnd_cde = I('c_brnd_cde');
            $c_drv_owner = I('c_drv_owner');
            $c_fst_reg_dte = I('c_fst_reg_dte');
            
            /*
            $uid = is_login();
            if($uid){
                   
            }else{
                //TODO:这里添加验证码验证
                $user = new UserApi;
                $uid = $user->login($mobile, $verify, 5);
                if(0 < $uid){ //UC登录成功
                    $Member = D('Member');
                    if($Member->login($uid)){ //登录用户
                    }
                } else { //登录失败
                    if($uid==-1){ //用户不存在
                        $uid = $User->register($mobile, $password, $email,$mobile);
                        if(0 < $uid){ //注册成功
                            //TODO: 发送验证邮件
                            
                        } else { //注册失败，显示错误信息
                            
                        }
                    }else{
                        $this->error("操作错误！");
                    }
                }
            }
            */

            //暂存数据到session
            session('brand',$brand);
            session('series',$series);
            session('model',$model);
            session('c_dpt_cde',$c_dpt_cde);
            session('c_new_vhl',$c_new_vhl);
            session('c_lcn_no',$c_lcn_no);
            session('c_eng_no',$c_eng_no);
            session('c_vhl_frm',$c_vhl_frm);
            session('c_drv_owner',$c_drv_owner);
            session('c_fst_reg_dte',$c_fst_reg_dte);
            session('mobile',$mobile);
            session('c_app_sex',$sex);
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1031');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_dpt_cde',$c_dpt_cde);
            $this->assign('c_lcn_no',$c_lcn_no);
            $this->assign('c_eng_no',$c_eng_no);
            $this->assign('c_vhl_frm',$c_vhl_frm);
            $this->assign('c_brnd_cde',$c_brnd_cde);
            $this->assign('c_drv_owner',$c_drv_owner);
            $this->assign('c_fst_reg_dte',$c_fst_reg_dte);            
            $xml = $this->fetch(T('Cic/GetCarInfo'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
            
            //Log::record(print_r($this->xmlToArray($ret),true));
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                //Log::record(print_r($retArr,true));
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $vhlmodel_list = array();
                    if(isset($retArr['VHLMODEL_LIST']['VHLMODEL'][0])){
                        foreach($retArr['VHLMODEL_LIST']['VHLMODEL'] as $model){
                            $vhlmodel_list[] = $model;
                        }
                    }else{
                        $vhlmodel_list[] = $retArr['VHLMODEL_LIST']['VHLMODEL'];
                    }
                    
                    session('vhlmodel_list',$vhlmodel_list);
                    $this->assign('vhlmodel_list',$vhlmodel_list);
                    
                    //假设商业险日期
                    $dtReg = new \DateTime($c_fst_reg_dte);
                    while($dtReg->getTimestamp()<$now->getTimestamp()){
                        //如果首登日期大于今天，则直接首登日期否则一年一年累加
                        $dtReg = $dtReg->add(new \DateInterval('P1Y'));
                    }
                    $t_insrnc_bgn_tm = $dtReg->format('Y-m-d');
                    
                    $this->assign('t_insrnc_bgn_tm',$t_insrnc_bgn_tm);
                    $this->display();
                }else{
                    $this->error($retArr['MAIN']['ERR_INFO'],null,10);
                }
            }
        }
        
        /**
        * 第三步
        * 
        */
        public function step3(){
            $index = I('model_indx');
            $t_insrnc_bgn_tm = I('t_insrnc_bgn_tm') . ' 00:00:00';

            $vhlmodel_list = session('vhlmodel_list');
            $vhlmodel = $vhlmodel_list[$index];  
            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            $t_oper_date = $now->format('Y-m-d');
            
            session('model_indx',$index);
            session('t_insrnc_bgn_tm',$t_insrnc_bgn_tm);
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1032');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_dpt_cde',session('c_dpt_cde'));
            $this->assign('t_insrnc_bgn_tm',$t_insrnc_bgn_tm);
            $this->assign('t_oper_date',$t_oper_date);
            
            $this->assign('c_lcn_no',session('c_lcn_no'));
            $this->assign('c_new_vhl',session('c_new_vhl'));
            $this->assign('c_drv_owner',session('c_drv_owner'));
            $this->assign('c_eng_no',session('c_eng_no'));
            $this->assign('c_vhl_frm',session('c_vhl_frm'));
            $this->assign('c_fst_reg_dte',session('c_fst_reg_dte'));            
            $this->assign('c_vehicle_code',$vhlmodel['C_VEHICLE_CODE']);
            $this->assign('c_vehicle_name',$vhlmodel['C_VEHICLE_NAME']);
            $this->assign('c_vehicle_brand',$vhlmodel['C_VEHICLE_BRAND']);
            $this->assign('n_vehicle_price',$vhlmodel['N_VEHICLE_PRICE']);
            $this->assign('n_limit_load_person',$vhlmodel['N_LIMIT_LOAD_PERSON']);
            $this->assign('c_ext_msr',$vhlmodel['C_EXT_MSR']);
            $this->assign('c_vehicle_family',$vhlmodel['C_VEHICLE_FAMILY']);
            $this->assign('c_import_flag',$vhlmodel['C_IMPORT_FLAG']);
            $this->assign('c_vehicle_model',$vhlmodel['C_VEHICLE_MODEL']);
            $this->assign('c_whole_weight',$vhlmodel['C_WHOLE_WEIGHT']);
            $this->assign('c_model_desc',$vhlmodel['C_MODEL_DESC']);
            $this->assign('n_vehicle_tonnage',$vhlmodel['N_VEHICLE_TONNAGE']);
            $this->assign('c_market_timestamp',$vhlmodel['C_MARKET_TIMESTAMP']);
            $xml = $this->fetch(T('Cic/Scheme'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
                      
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                //Log::record(print_r($retArr,true));
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $c_order_no = $retArr['BASE']['C_ORDER_NO'];
                    session('c_order_no',$c_order_no);
                    if($retArr['BASE']['C_LAST_BUS_END']){
                        session('c_last_bus_end',$retArr['BASE']['C_LAST_BUS_END']);
                    }
                    if($retArr['BASE']['C_LAST_TRA_END']){
                        session('c_last_tra_end',$retArr['BASE']['C_LAST_TRA_END']);
                    }
                    $kindlist = array();
                    foreach($retArr['KIND_LIST']['KIND'] as $kind){
                        $kind['opts'] = json_decode($kind['C_AMT_LIST'],true);
                        $kindlist[] = $kind;
                    }
                    session('kindlist',$kindlist);
                    /*   */
                    $this->assign('c_order_no',$c_order_no);
                    $this->assign('kindlist',$kindlist);
                    $this->display();     /**/
                    //print_r($retXml);
                }else{
                    $this->error($retArr['MAIN']['ERR_INFO'],null,10);
                }
            } 
        }
        
        /**
        * 获取保险名称
        * 
        * @param mixed $kind_cde
        */
        protected function getKindName($kind_list,$kind_cde){
            $ret = '';
            foreach($kind_list as $kind){
                if($kind['C_KIND_CDE'] == $kind_cde){
                    $ret = $kind['C_KIND_NAME'];
                    break;
                }
            }
            return $ret;
        }
        
        /**
        * 第四步
        * 
        */
        public function step4(){
            $c_kind_cde = session('kindlist');
            $n_amt = I('n_amt');
            $n_seat_num = I('n_seat_num');
            $t_insrnc_bgn_tm = I('t_insrnc_bgn_tm');
            $kinds = array();
            foreach($n_amt as $key => $kind){
                $kinds[] = array(
                    'seq_no' => $key,
                    'c_kind_cde' => $key,
                    'n_amt' => $n_amt[$key],
                    'n_seat_num' => $n_seat_num[$key],
                );
            }
            session('kinds',$kinds);

            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            $t_oper_date = $now->format('Y-m-d');
            $c_order_no = I('c_order_no');
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1033');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_dpt_cde',session('c_dpt_cde'));
            $this->assign('c_order_no',$c_order_no);
            $this->assign('t_insrnc_bgn_tm',$t_insrnc_bgn_tm);
            $this->assign('t_traff_bgn_tm',$t_insrnc_bgn_tm);
            $this->assign('t_ys_flag','0');  //约省
            
            $this->assign('fuel_type','0');
            $this->assign('buy_date',session('c_fst_reg_dte'));
            
            $this->assign('kinds',$kinds);
            
            $xml = $this->fetch(T('Cic/CalcFee'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
            
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                //Log::record(print_r($retArr,true));
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $this->assign('c_order_no',$retArr['BASE']['C_ORDER_NO']);
                    $this->assign('n_real_prm',$retArr['BASE']['N_REAL_PRM']);
                    $this->assign('n_prm',$retArr['BASE']['N_PRM']);
                    $this->assign('n_traff_real_prm',$retArr['BASE']['N_TRAFF_REAL_PRM']);
                    $this->assign('n_traff_prm',$retArr['BASE']['N_TRAFF_PRM']);
                    $this->assign('n_tax_real_prm',$retArr['BASE']['N_TAX_REAL_PRM']);
                    $this->assign('n_tax_prm',$retArr['BASE']['N_TAX_PRM']);
                    
                    $kindlist = array();
                    foreach($retArr['KIND_LIST']['KIND'] as $kind){
                        $kind['C_KIND_NAME'] = $this->getKindName($c_kind_cde,$kind['C_KIND_CDE']);
                        $kindlist[] = $kind;
                    }
                    
                    $uid = is_login();
                    if($uid){
                        $modelAddress = M('UserAddress');
                        $where['uid'] = $uid;
                        $address = $modelAddress->where($where)->select();
                        $this->assign('address',$address);
                        $modelMember = M('Member');
                        $user = $modelMember->where("uid=$uid")->find();
                        $this->assign('user',$user);
                    }
                    
                    $vhlmodel_list = session('vhlmodel_list');
                    //Log::record(print_r($vhlmodel_list,true));
                    $indx = session('model_indx');
                    //Log::record(print_r($indx,true));
                    $vhlInfo = $vhlmodel_list[$indx];
                    
                    $this->assign('c_lcn_no',session('c_lcn_no'));
                    $this->assign('c_drv_owner',session('c_drv_owner'));
                    $this->assign('vhlinfo',$vhlInfo);
                    $this->assign('kindlist',$kindlist);
                    $this->display();     
                    
                }else{
                    $this->error($retArr['MAIN']['ERR_INFO'],null,10000);
                }
            } 
        }
        
        public function step5(){

            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            
            $aid = I('aid');
            if(empty($aid)){
                $this->error('错误的地址！');
            }
            $modelAddress = M('UserAddress');
            $resAddress = $modelAddress->where("aid=$aid")->find();
            if($resAddress){
                $address = $resAddress['province'] .$resAddress['city'].$resAddress['area'].$resAddress['address'];
            }else{
                $this->error('错误的地址！');
            }
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1036');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_dpt_cde',session('c_dpt_cde'));
            
            $c_order_no = session('c_order_no');
            $this->assign('c_order_no',$c_order_no);
            $this->assign('c_drv_owner',session('c_drv_owner'));
            $this->assign('c_ident_type','01');
            $this->assign('c_ident_no',I('c_ident_no'));
            $this->assign('c_app_nme',session('c_drv_owner'));
            $this->assign('c_app_sex',session('c_app_sex'));
            $this->assign('c_app_ident_type','01');
            $this->assign('c_app_ident_no',I('c_ident_no'));
            $this->assign('c_app_tel',session('mobile'));
            $this->assign('c_app_addr',$address);
            $this->assign('c_app_email',I('c_app_email'));
            $this->assign('c_insrnt_nme',session('c_drv_owner'));
            $this->assign('c_insrnt_sex',session('c_app_sex'));
            $this->assign('c_insrnt_ident_type','01');
            $this->assign('c_insrnt_ident_no',I('c_ident_no'));
            $this->assign('c_insrnt_tel',session('mobile'));
            $this->assign('c_insrnt_addr',$address);
            $this->assign('c_insrnt_email',I('c_app_email'));
            $this->assign('c_contact_name',$resAddress['recvname']);
            $this->assign('c_contact_tel',$resAddress['mobile']);
            $this->assign('c_contact_email',I('c_app_email'));
            $this->assign('c_address',$address);
            $xml = $this->fetch(T('Cic/VerifyInfo'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
            
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                //Log::record(print_r($retArr,true));
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $this->redirect('Insurance/confirm',array('c_order_no'=>$c_order_no,'token'=>date('YmdHis')));
                }else{
                    $this->error($retArr['MAIN']['ERR_INFO'],null,10);
                }
            } 
        }
        
        public function confirm(){
            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            
            $c_order_no = I('c_order_no');
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1037');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_order_no',$c_order_no);
            $xml = $this->fetch(T('Cic/Confirm'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
            
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $model = M('CicOrder');
                    unset($data);
                    $data['c_order_no'] = $c_order_no;
                    $data['serialdecimal'] = $retArr['MAIN']['SERIALDECIMAL'];
                    $data['transrdate'] = $retArr['MAIN']['TRANSRDATE'];
                    $data['c_dpt_cde'] = session('c_dpt_cde');
                    $data['t_insrnc_bgn_tm'] = $retArr['INSURANCE']['T_INSRNC_BGN_TM'];
                    $data['t_insrnc_end_tm'] = $retArr['INSURANCE']['T_INSRNC_END_TM'];
                    $data['t_traff_bgn_tm'] = $retArr['INSURANCE']['T_TRAFF_BGN_TM'];
                    $data['t_traff_end_tm'] = $retArr['INSURANCE']['T_TRAFF_END_TM'];
                    $data['n_real_amt'] = $retArr['INSURANCE']['N_REAL_AMT'];
                    $data['n_prm'] = $retArr['INSURANCE']['N_PRM'];
                    $data['n_traff_real_prm'] = $retArr['INSURANCE']['N_TRAFF_REAL_PRM'];
                    $data['n_traff_prm'] = $retArr['INSURANCE']['N_TRAFF_PRM'];
                    $data['n_tax_real_prm'] = $retArr['INSURANCE']['N_TAX_REAL_PRM'];
                    $data['n_tax_prm'] = $retArr['INSURANCE']['N_TAX_PRM'];
                    $data['c_appnt'] = $retArr['INSURANCE']['N_TAX_PRM'];
                    $data['c_tax_appnt'] = $retArr['INSURANCE']['N_TAX_PRM'];
                    $data['c_remark'] = $retArr['INSURANCE']['C_REMARK'];
                    $data['c_app_nme'] = $retArr['PARTICIPANT']['C_APP_NME'];
                    $data['c_app_sex'] = $retArr['PARTICIPANT']['C_APP_SEX'];
                    $data['c_app_ident_type'] = $retArr['PARTICIPANT']['C_APP_IDENT_TYPE'];
                    $data['c_app_ident_no'] = $retArr['PARTICIPANT']['C_APP_IDENT_NO'];
                    $data['c_app_tel'] = $retArr['PARTICIPANT']['C_APP_TEL'];
                    $data['c_app_addr'] = $retArr['PARTICIPANT']['C_APP_ADDR'];
                    $data['c_app_email'] = $retArr['PARTICIPANT']['C_APP_EMAIL'];
                    $data['c_app_zipcode'] = $retArr['PARTICIPANT']['C_APP_ZIPCODE'];
                    $data['c_insrnt_nme'] = $retArr['PARTICIPANT']['C_INSRNT_NME'];
                    $data['c_insrnt_sex'] = $retArr['PARTICIPANT']['C_INSRNT_SEX'];
                    $data['c_insrnt_ident_type'] = $retArr['PARTICIPANT']['C_INSRNT_IDENT_TYPE'];
                    $data['c_insrnt_ident_no'] = $retArr['PARTICIPANT']['C_INSRNT_IDENT_NO'];
                    $data['c_insrnt_tel'] = $retArr['PARTICIPANT']['C_INSRNT_TEL'];
                    $data['c_insrnt_addr'] = $retArr['PARTICIPANT']['C_INSRNT_ADDR'];
                    $data['c_insrnt_email'] = $retArr['PARTICIPANT']['C_INSRNT_EMAIL'];
                    $data['c_insrnt_zipcode'] = $retArr['PARTICIPANT']['C_INSRNT_ZIPCODE'];
                    $data['c_contact_name'] = $retArr['PARTICIPANT']['C_CONTACT_NAME'];
                    $data['c_contact_tel'] = $retArr['PARTICIPANT']['C_CONTACT_TEL'];
                    $data['c_contact_email'] = $retArr['PARTICIPANT']['C_APP_NME'];
                    $data['c_address'] = $retArr['PARTICIPANT']['C_ADDRESS'];
                    $data['c_drv_owner'] = $retArr['VHL']['C_DRV_OWNER'];
                    $data['c_ident_type'] = $retArr['VHL']['C_IDENT_TYPE'];
                    $data['c_ident_no'] = $retArr['VHL']['C_IDENT_NO'];
                    $data['c_vehicle_brand'] = $retArr['VHL']['C_VEHICLE_BRAND'];
                    $data['c_brnd_cde'] = $retArr['VHL']['C_BRND_CDE'];
                    $data['c_vehicle_name'] = $retArr['VHL']['C_VEHICLE_NAME'];
                    $data['c_noclm_amt_cde'] = $retArr['VHL']['C_NOCLM_AMT_CDE'];
                    $data['c_vin_cde'] = $retArr['VHL']['C_VIN_CDE'];
                    $data['c_lcn_no'] = $retArr['VHL']['C_LCN_NO'];
                    $data['c_vhl_frm'] = $retArr['VHL']['C_VHL_FRM'];
                    $data['c_eng_no'] = $retArr['VHL']['C_ENG_NO'];
                    $data['c_fee_atr'] = $retArr['VHL']['C_FEE_ATR'];
                    $data['c_fst_reg_dte'] = $retArr['VHL']['C_FST_REG_DTE'];
                    $data['n_limit_load_person'] = $retArr['VHL']['N_LIMIT_LOAD_PERSON'];
                    $data['c_whole_weight'] = $retArr['VHL']['C_WHOLE_WEIGHT'];
                    $data['c_ext_msr'] = $retArr['VHL']['C_EXT_MSR'];
                    $data['c_power_type'] = $retArr['VHL']['C_POWER_TYPE'];
                    $data['n_vehicle_price'] = $retArr['VHL']['N_VEHICLE_PRICE'];
                    $data['c_import_flag'] = $retArr['VHL']['C_IMPORT_FLAG'];

                    unset($where);
                    $where['c_order_no'] = $c_order_no;
                    $resCic = $model->where($where)->find();
                    if($resCic){
                        $orderid = $resCic['corder_id'];
                        $model->where($where)->save($data);
                    }else{
                        $orderid = $model->add($data);
                    }
                    
                    $modelDetail = M('CicOrderDetail');
                    $modelDetail->where("corder_id=$orderid")->delete();
                    foreach($retArr['KIND_LIST']['KIND'] as $kind){
                        unset($d);
                        $d['corder_id'] = $orderid;
                        $d['n_seq_no'] = $kind['N_SEQ_NO'];
                        $d['c_kind_cde'] = $kind['C_KIND_CDE'];
                        $d['c_kind_name'] = $kind['C_KIND_NAME'];
                        $d['n_amt'] = $kind['N_AMT'];
                        $d['n_prm'] = $kind['N_PRM'];
                        $d['n_seatnum'] = $kind['N_SEATNUM'];
                        $modelDetail->add($d);
                    }
                    
                    //print_r($retXml);
                    $this->assign('data',$data);
                    $this->display();
                }else{
                    $this->error($xmlMain->ERR_INFO,null,10);
                }
            } 
            
        }
        
        public function finish(){
            $now = new \DateTime();
            $business_code = '13';
            $transrdate = $now->format('Y-m-d H:i:s');
            $serialdecimal = get_serial_no();
            
            $c_order_no = session('c_order_no');
            $sendtype = I('sendtype',1);
            $c_payment_type = I('c_payment_type');
            
            //开始封装传入中华的数据
            $this->initTemplData();
            $this->assign('business_code',$business_code);
            $this->assign('serialdecimal',$serialdecimal);
            $this->assign('transrno','1038');
            $this->assign('transrdate',$transrdate);
            $this->assign('c_order_no',$c_order_no);
            $this->assign('c_payment_type',$c_payment_type);
            $xml = $this->fetch(T('Cic/Buy'));
            
            //请求中华保险接口
            $ret = $this->getData($xml);
            
            $retXml = simplexml_load_string($ret);
            if($retXml === false){
                $this->error('接口无响应或返回异常，请联系管理员');
            }else{
                $retArr = $this->xmlToArray($ret);
                //Log::record(print_r($retArr,true));
                if($retArr['MAIN']['RESULTCODE'] == '0000'){
                    $modelCic = M('CicOrder');
                    $modelDh = M('CicOrderDh');
                    unset($where);
                    $where['c_order_no'] = $c_order_no;
                    $resCic = $modelCic->where($where)->find();
                    if($resCic){
                        //记录保单号
                        foreach($retArr['POLICY_LIST']['POLICY'] as $policy){
                            unset($data);
                            $data['corder_id'] = $resCic['corder_id'];
                            $data['c_proposal_no'] = $policy['C_PROPOSAL_NO'];
                            $data['business_code'] = $policy['BUSINESS_CODE'];
                            $modelDh->add($data);
                        }
                        
                        //记录订单
                        $uid = is_login();
                        if($uid){
                            $product_id = 1; //目前仅有一种
                            $modelProduct = M('Product');
                            $resProduct = $modelProduct->where("product_id=$product_id")->find();
                            if($resProduct){//记录订单，获取日收益和日冻结收益金额
                                $tableName = $resProduct['order_table'];
                                $day_amt_fun = $resProduct['day_amt_fun'];
                                $day_frozen_amt_fun = $resProduct['day_frozen_amt_fun'];
                                $primary_key = $resProduct['primary_key'];
                                $targetId = $resCic['corder_id'];
                                
                                $modelTable = M($tableName);
                                $resAmt = $modelTable->query("select ($day_amt_fun) as day_amt,($day_frozen_amt_fun) as day_frozen_amt from __TABLE__ where $primary_key=$targetId");
                                if(!empty($resAmt)){
                                    $day_amt = $resAmt[0]['day_amt'];
                                    $day_frozen_amt = $resAmt[0]['day_frozen_amt'];
                                }else{
                                    $day_amt = 0;
                                    $day_frozen_amt = 0;
                                }
                                
                                $modelOrder = M('Order');
                                unset($data);
                                $data['order_no'] = $resCic['c_order_no'];
                                $data['uid'] = $uid;
                                $data['product_id'] = $product_id;
                                $data['posttime'] = date('Y-m-d H:i:s');
                                $data['car_no'] = $resCic['c_lcn_no'];//记录车牌号码
                                $data['targetid'] = $targetId;
                                $data['sendtype'] = $sendtype;
                                $data['start_date'] = $resCic['t_insrnc_bgn_tm'];
                                $data['end_date'] = $resCic['t_insrnc_end_tm'];
                                $data['day_amt'] = $day_amt;
                                $data['day_frozen_amt'] = $day_frozen_amt;
                                $data['n_real_amt'] = $resCic['n_real_amt'];
                                $data['n_traff_real_prm'] = $resCic['n_traff_real_prm'];
                                $data['n_tax_real_prm'] = $resCic['n_tax_real_prm'];
                                $modelOrder->add($data);
                                
                                //自动增加车辆信息
                                $modelCar = M('UserCar');
                                unset($where);
                                $where['uid'] = $uid;
                                $where['c_lcn_no'] = $resCic['c_lcn_no'];
                                $resCar = $modelCar->where($where)->find();
                                unset($data);
                                $data['uid'] = $uid;
                                $data['c_vehicle_brand'] = $resCic['c_vehicle_brand'];
                                $data['c_brnd_cde'] = $resCic['c_brnd_cde'];
                                $data['c_vehicle_name'] = $resCic['c_vehicle_name'];
                                $data['c_fee_atr'] = $resCic['c_fee_atr'];
                                $data['c_lcn_no'] = $resCic['c_lcn_no'];
                                $data['c_vin_cde'] = $resCic['c_vin_cde'];
                                $data['c_vhl_frm'] = $resCic['c_vhl_frm'];
                                $data['c_eng_no'] = $resCic['c_eng_no'];
                                $data['c_fst_reg_dte'] = $resCic['c_fst_reg_dte'];
                                $data['n_limit_load_person'] = $resCic['n_limit_load_person'];
                                $data['c_whole_weight'] = $resCic['c_whole_weight'];
                                $data['c_ext_msr'] = $resCic['c_ext_msr'];
                                $data['c_power_type'] = $resCic['c_power_type'];
                                $data['n_vehicle_price'] = $resCic['n_vehicle_price'];
                                $data['c_import_flag'] = $resCic['c_import_flag'];
                                if($resCar){
                                    $modelCar->where("car_id={$resCar['car_id']}")->save($data);
                                }else{
                                    $modelCar->add($data);
                                }
                            }
                        }                    
                    }
                    if($c_payment_type == '01'){
                        redirect(C('CIC_PAY_URL').$c_order_no);
                    }else{
                        $this->redirect('User/index');
                    }
                }else{
                    $this->error($retArr['MAIN']['ERR_INFO'],null,10);
                }
            } 
        }
        
        protected function xmlNameSpaceToArray(\SimpleXmlIterator $xml, $nameSpaces=Null){
              $output = Null;
              $preparedArray = array();
              for($xml->rewind(); $xml->valid(); $xml->next()) {
                    $key = $xml->key();
                    if(!isset($preparedArray[$key])) { $preparedArray[$key] = array(); $i=0; }
                    else $i = count($preparedArray[$key]);
                    $simple = true;
                    foreach($xml->current()->attributes() as $k=>$v) {
                        $preparedArray[$key][$i][$k]=(string)$v;
                        $simple = false;
                    }
                    if($nameSpaces) foreach($nameSpaces as $nid=>$name) {
                    foreach($xml->current()->attributes($name) as $k=>$v) {
                        $preparedArray[$key][$i][$nid.':'.$k]=(string)$v;
                        $simple = false;
                    }
                    } 
                    if($xml->hasChildren()) {
                        if($simple) $preparedArray[$key][$i] = $this->xmlNameSpaceToArray($xml->current(), $nameSpaces);
                        else $preparedArray[$key][$i]['content'] = $this->xmlNameSpaceToArray($xml->current(), $nameSpaces);
                    } else {
                        if($simple) $preparedArray[$key][$i] = strval($xml->current());
                        else $preparedArray[$key][$i]['content'] = strval($xml->current());
                    }
                    $i++;
              }
              $output = $preparedArray;
              return $preparedArray;
        }
        
        protected function simpleArray(&$array){
            if(is_array($array)){
                if(count($array)==1){//只有一个元素
                    if(isset($array[0])){
                        $array = $array[0];
                        $this->simpleArray($array);
                    }else{
                        foreach($array as &$item){
                            $this->simpleArray($item);
                        }
                    }
                }else{
                    foreach($array as &$item){
                        $this->simpleArray($item);
                    }
                }
            }
        }
         
        protected function xmlToArray($xmldata){
            $xml = new \SimpleXmlIterator($xmldata);
            $nameSpaces = $xml->getNamespaces(true);
            $output = $this->xmlNameSpaceToArray($xml,$nameSpaces);
            $this->simpleArray($output);
            return $output;
        }
        
        protected function xml2array($in){
            $ret = array();
            try{
                $xml = (array)$in;
                foreach($xml as $key => $val){
                    $ret[$key] =  $val;
                }
            }catch(Exception $e){
                
            }
            return $ret;
        }
        
        protected function xml2object($xml,$force = false){

            $obj = new \StdClass();    

            $obj->name = $xml->getName();
            
            $text = trim((string)$xml);
            $attributes = array();
            $children = array();
            
            foreach($xml->attributes() as $k => $v){
                $attributes[$k]  = (string)$v;
            }
            
            foreach($xml->children() as $k => $v){
                $children[] = $this->xml2object($v,$force);
            }
            
            
            if($force or $text !== '')
                $obj->text = $text;
                
            if($force or count($attributes) > 0)
                $obj->attributes = $attributes;
                
            if($force or count($children) > 0)
                $obj->children = $children;
            return $obj;
        }


        /**
        * 从中华保险接口中获取相应信息
        * 
        * @param mixed $xml 请求内容
        * @return mixed 返回中华保险接口返回的xml内容，失败的话返回false
        */
        protected function getData($xml){
            try{
                Log::record($xml);
                $client = new \SoapClient(C('CIC_URL'));
                $param = array('content' => $xml);
                $data = $client->getRequest($param);
                Log::record($data->return);
            }catch(Execption $e){
                return false;            
            }
            return $data->return;
        }

        /**
        * 初始化接口需要的公共模板变量
        * 
        */
        protected function initTemplData(){
            $this->assign('user_name',C('CIC_ECUSER'));
            $this->assign('user_psw',C('CIC_ECPASS'));
            $this->assign('channelcode',C('CIC_CHANNELCODE'));
        }


        /**
        * 分析返回值
        * 
        * @param mixed $xml
        */
        protected function parseReturn($xml){
            try{
                $ret = new \SimpleXMLElement($xml);        
            }catch(Execption $e){
                return false;
            }
        }

        protected function print_xml($xml){
            header("Content-type:text/xml");
            echo $xml;
        }

}